﻿using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;


namespace ModelRelationship
{

    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
        public string NickName { get; set; }
        [ForeignKey("UserId")] //①
        [InverseProperty("User")]
        public UserInfo UserInfo { get; set; }
    }

    public class UserInfo
    {
        public int Id { get; set; }
        public string NickName { get; set; }
        public string PersonTag { get; set; }
        [ForeignKey("User")] //①③
        public int? UserId { get; set; }
        [ForeignKey("UserId")] //①③
        [InverseProperty("UserInfo")] //②③
        public User User { get; set; }
    }


    /// <summary>
    /// 表共享
    /// </summary>
    public class OneToOneRelationshipDbContext : DbContext
    {
        public DbSet<User> Users => Set<User>();

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<User>(
                b =>
                {
                    b.OwnsOne(u => u.UserInfo)
                    .ToString();
                });

            modelBuilder.Entity<User>(
                b =>
                {
                    b.HasOne(u => u.UserInfo).WithOne(ui => ui.User)
                    .HasForeignKey<UserInfo>(ui => ui.UserId);
                });

            modelBuilder.Entity<UserInfo>(b =>
            {
                b.HasOne(ui => ui.User).WithOne(u => u.UserInfo).HasForeignKey<UserInfo>(ui => ui.UserId);
            });
        }

    }
}
